package com.srwl.mytx.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MultiPointItem;
import com.amap.api.maps.model.MultiPointOverlay;
import com.amap.api.maps.model.MultiPointOverlayOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.domain.Contact;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.SearchHistoryAdapter;
import com.srwl.mytx.adapter.SearchResultAdapter;
import com.srwl.mytx.domain.AmapTopic;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.PreferenceManager;
import com.srwl.mytx.widget.BottomDialog;
import com.srwl.mytx.widget.ContactListView;
import com.srwl.mytx.activity.ChatActivity;
import com.srwl.mytx.activity.MainActivity;
import com.srwl.mytx.activity.PublishTopicActivity;
import com.srwl.mytx.activity.TopicDetailsActivity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by dahai2070 on 2016/8/23 0023.
 */
public class HomePageFragment extends BaseFragment implements View.OnClickListener, AMap.OnMyLocationChangeListener, AMapLocationListener {
    private static final String TAG = HomePageFragment.class.getSimpleName();
    public static final int REQUEST_CODE_TO_TOPIC_DETAIL_FROM_SEARCH = 1;
    public static final int REQUEST_CODE_TO_TOPIC_DETAIL_FROM_PUSH_MESSAGE = 2;
    private static final int MAKER_HEIGHT = 40;//单位dp
    private ProgressBar progressBar;
    private MapView mapView = null;
    public AMap aMap = null;
    private UiSettings mUiSettings;

    private Marker mMarker;
    private DrawerLayout mDrawerLayout;
    private ExpandableListView listView;
    private ContactListView contactListView;
    // private ExpandableAdapter adapter;
    private RecyclerView rl_search;
    private SearchHistoryAdapter searchHistoryAdapter;
    private SearchResultAdapter searchResultAdapter;
    private View view;
    private ImageButton btnMapstatus;
    private ImageView iv_release;
    private ImageButton btn3d;
    private TextView tv_first_title;
    private TextView tv_second_title;
    private TextView tv_third_title;
    private SearchView searchView;
    protected boolean hidden;
    private Map<String, List<Contact>> childMap = new HashMap<>();
    private List<String> parentList = new ArrayList<>();
    private List<String> searchHistoryList = new ArrayList<>();
    private List<Topic> searchResultList = new ArrayList<>();
    private long startTime = 0;
    private int changeCount = 0;
    private float lastY = 0;
    private float lastX = 0;
    private boolean bol_directionDown = true;
    private boolean bol_directionRight = true;
    boolean bol_firstSlide = true;

    boolean bol_hasClear = false;//标记单次屏幕事件中是否已经清除了地图覆盖物
    private MyLocationStyle myLocationStyle;
    private boolean showSearchResult;
    private boolean firstLocation = true;
    private AMapLocationClient mLocationClient;
    //第一次推送topic信息是否展示的标志
    private boolean isShowFirstPushTopic;
    private final static int SLIDE_CHANGE_DIRECTION_THRESHOLD = 15;//滑动换向检测阈值
    private boolean isNearbySearching;
    private LatLng lastCameraCenter;//上一次地图中心点
    private float lastZoom;//上一次的地图缩放级别
    private Topic pushTopic;
    private boolean followMove = true;
    private RelativeLayout rl_topbar;
    private ImageView iv_switch;
    private MainActivity.ChangeFragmentListener listener;



    public void setListener(MainActivity.ChangeFragmentListener listener) {
        this.listener = listener;
    }

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home_page_map, container, false);
        progressBar = view.findViewById(R.id.progress_bar);
        mapView = view.findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);
        mDrawerLayout = view.findViewById(R.id.drawer_layout);
        btnMapstatus = view.findViewById(R.id.btn_map_status);
        btn3d = view.findViewById(R.id.btn3d);
        iv_release = view.findViewById(R.id.iv_release);
        iv_release.setOnClickListener(this);
        rl_search = view.findViewById(R.id.rl_search);
        btnMapstatus.setOnClickListener(this);
        btn3d.setOnClickListener(this);
        rl_topbar = view.findViewById(R.id.rl_topbar);
        tv_first_title = view.findViewById(R.id.tv_first_title);
        tv_second_title = view.findViewById(R.id.tv_second_title);
        tv_third_title = view.findViewById(R.id.tv_third_title);
        tv_first_title.setOnClickListener(this);
        tv_second_title.setOnClickListener(this);
        tv_third_title.setOnClickListener(this);
        iv_switch = view.findViewById(R.id.iv_switch);
        iv_switch.setOnClickListener(this);
        initSearchView();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initLocation();

    }

    private void initSearchView() {
        searchView = view.findViewById(R.id.search_view);
        searchView.setSubmitButtonEnabled(true);
        searchView.setIconifiedByDefault(false);
        searchView.setFocusable(false);
        searchView.setOnQueryTextListener(getQueryTextListener());
        initSearchHistoryListView();
        //这儿动态设置背景，不知道为什么，在布局文件里面设置了没有效果
        //去下划线
        searchView.findViewById(R.id.search_plate).setBackground(null);
        searchView.findViewById(R.id.submit_area).setBackground(null);
        searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    rl_topbar.setVisibility(View.GONE);
                    showSearchHistory();
                    rl_search.setVisibility(View.VISIBLE);
                } else {
                    rl_topbar.setVisibility(View.VISIBLE);
                    rl_search.setVisibility(View.GONE);
                }

            }
        });
        searchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                closeSearchView();
                rl_topbar.setVisibility(View.VISIBLE);
                return false;
            }
        });
        searchView.setOnSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchView.setBackground(new ColorDrawable(Color.WHITE));
                showSearchHistory();
                rl_search.setVisibility(View.VISIBLE);
                //  iv_release.setVisibility(View.GONE);
            }
        });
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                //把查询内容添加进搜索历史
                if (!searchHistoryList.contains(query)) {
                    searchHistoryList.add(0, query);
                    PreferenceManager.getInstance().setCurrentUserSearchHistoryTopic(searchHistoryList);
                    searchHistoryAdapter.notifyDataSetChanged();
                }
                search(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                //如果输入框没有内容，显示搜索历史
                if (newText == null || newText.equals("")) {
                    showSearchHistory();
                }
                //做搜索建议
                return false;
            }
        });
        ItemTouchHelper touchHelper = new ItemTouchHelper(new MyItemTouchHelperCallBack());

        touchHelper.attachToRecyclerView(rl_search);

    }

    void showSearchHistory() {
        showSearchResult = false;
        rl_search.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
        rl_search.setAdapter(searchHistoryAdapter);
    }

    private void initSearchHistoryListView() {
        List<String> currentUserSearchHistory = PreferenceManager.getInstance().getCurrentUserSearchHistoryTopic();
        if (currentUserSearchHistory != null) {
            searchHistoryList.addAll(currentUserSearchHistory);
        }
        // TODO: 2019-10-08  
        //searchHistoryAdapter = new SearchHistoryAdapter(getContext(), searchHistoryList);
        searchHistoryAdapter.setSearchHistoryItemClickListener(new SearchHistoryAdapter.SearchHistoryItemClickListener() {
            @Override
            public void onItemClick(int position) {

            }

            @Override
            public void onItemLongClick(int position) {

            }

//            @Override
//            public void onItemClick(SearchHistoryAdapter.MyViewHolder viewHolder) {
//                hideSoftKeyboard();
//                search(searchHistoryList.get(viewHolder.getAdapterPosition()));
//                viewHolder.progressBar.setVisibility(View.VISIBLE);
//                // aMapSearch(searchHistoryList.get(position), null, "全国", Constant.AMAP_SAERCH_TYPE_LOCAL);
//            }
        });

    }

    private void initContactListView() {
        //getContactList();
        // listView = view.findViewById(R.id.left_drawer);
        //listView.getBackground().setAlpha(175);
//        contactListView = view.findViewById(R.id.contact_list_view);
//        contactListView.login(Helper.getInstance().getContactList());
//        contactListView.setListener(new ContactListView.InteractionListener() {
//            @Override
//            public void onContactDelete() {
//                ((MainActivity) getActivity()).updateUnreadLabel();//更新未读红点
//            }
//        });
//        adapter = new ExpandableAdapter(getActivity(), parentList, childMap);
//        adapter.setItemClickListener(new ExpandableAdapter.ItemClickListener() {
//            @Override
//            public void groupItemClick() {
//
//            }
//
//            @Override
//            public void childItemClick() {
//
//            }
//
//            @Override
//            public void childItemShowDialogClick(Contact contact) {
//                childViewGetMoreClick(contact);
//            }
//        });
        //listView.setAdapter(adapter);
        //listView.setLayoutParams(params);
    }


    private void initLocation() {


        aMap = mapView.getMap();
        mUiSettings = aMap.getUiSettings();

        //设置不显示指南针
        mUiSettings.setCompassEnabled(false);
        //显示定位按键
        mUiSettings.setMyLocationButtonEnabled(false);
        myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);// LOCATION_TYPE_LOCATE:定位一次 ，地图移动到定位地点 LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER:连续定位，图标转动，
        myLocationStyle.showMyLocation(true);
        myLocationStyle.anchor(0.5f, 0.5f);
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.compass3));
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.strokeWidth(1f);
        myLocationStyle.interval(5000);//连续定位模式下的定位间隔时间
        aMap.setMyLocationStyle(myLocationStyle);
        // 是否可触发定位并显示定位层
        aMap.setMyLocationEnabled(true);
        mUiSettings.setZoomControlsEnabled(false);

        //设置缩放级别
        aMap.animateCamera(CameraUpdateFactory.zoomTo(17));
        //设置地图倾斜度

        aMap.animateCamera(CameraUpdateFactory.changeTilt(30));

        aMap.setOnMyLocationChangeListener(this);
        mLocationClient = new AMapLocationClient(getActivity().getApplicationContext());     //声明LocationClient类
        mLocationClient.setLocationListener(this);    //注册监听函数
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
//该方法默认为false。
        mLocationOption.setOnceLocation(true);
//关闭缓存机制
        // mLocationOption.setLocationCacheEnable(false);

        //     mLocationClient = new AMapLocationClient(getActivity().getApplicationContext());     //声明LocationClient类
//        mLocationClient.setLocationListener(this);    //注册监听函数
//        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        //设置定位间隔,单位毫秒,默认为2000ms
//        mLocationOption.setInterval(2000);
//
//
//        mLocationClient.setLocationOption(mLocationOption);
//        if (!mLocationClient.isStarted()) {
//            mLocationClient.startLocation();
//        }


        aMap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                //用户拖动地图后，不再跟随移动，直到用户点击定位按钮

                followMove = false;

                if (!followMove) {
                    if (myLocationStyle.getMyLocationType() != MyLocationStyle.LOCATION_TYPE_MAP_ROTATE_NO_CENTER) {

                        //mBaiduMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW));
                        btnMapstatus.setBackgroundResource(R.drawable.tx_map_location);
                        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.compass3));
                        //btn_trackQuery.setVisibility(View.VISIBLE);
                        //btnMapstatus.setVisibility(View.INVISIBLE);
                    } else {
                        aMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER));
                    }

                }

                float currentX = motionEvent.getX();
                float currentY = motionEvent.getY();
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startTime = motionEvent.getDownTime();
                        break;

                    case MotionEvent.ACTION_MOVE:
                        if (bol_firstSlide) {//首次进入滑动状态，设置X、Y方向参考点
                            bol_firstSlide = false;
                            lastX = currentX;
                            lastY = currentY;
                            return;
                        }
                        //检测X方向的滑动换向
                        if (currentX - lastX > 0) {//此刻向右滑动
                            if (!bol_directionRight) {//发生换向，重置参考点
                                if (currentX - lastX > SLIDE_CHANGE_DIRECTION_THRESHOLD) {//滑动距离超过阈值，判定为已经换向
                                    changeCount += 1;
                                    //  Log.d(TAG, "onTouch: 向右换向" + changeCount);
                                }
                                //   lastX = currentX;
                            }
                            //设置当前为向右滑动
                            bol_directionRight = true;

                        } else if (currentX - lastX < 0) {//此刻向左边滑动

                            if (bol_directionRight) {//发生换向，重置参考点
                                if (Math.abs(currentX - lastX) > SLIDE_CHANGE_DIRECTION_THRESHOLD) {//滑动距离超过阈值，判定为已经换向
                                    changeCount += 1;
                                    //  Log.d(TAG, "onTouch: 向左换向" + changeCount);
                                }
                                // lastX = currentX;
                            }
                            //设置当前为向左滑动
                            bol_directionRight = false;
                        }

                        //检测Y方向的滑动换向

                        if (currentY - lastY > 0) {//此刻向下滑动
                            if (!bol_directionDown) {//发生换向，重置参考点
                                if (currentY - lastY > SLIDE_CHANGE_DIRECTION_THRESHOLD) {//滑动距离超过阈值，判定为已经换向
                                    changeCount += 1;
                                    // Log.d(TAG, "onTouch: 向下换向" + changeCount);
                                }
                                // lastY = currentY;
                            }
                            //设置当前为向下滑动
                            bol_directionDown = true;

                        } else if (currentY - lastY < 0) {//此刻向上边滑动

                            if (bol_directionDown) {//发生换向，重置参考点
                                if (Math.abs(currentY - lastY) > SLIDE_CHANGE_DIRECTION_THRESHOLD) {//滑动距离超过阈值，判定为已经换向
                                    changeCount += 1;
                                    //  Log.d(TAG, "onTouch: 向上换向" + changeCount);
                                }
                                // lastY = currentY;
                            }
                            //设置当前为向上滑动
                            bol_directionDown = false;
                        }
                        lastX = currentX;
                        lastY = currentY;
                        long currentTime = motionEvent.getDownTime();
                        if (changeCount >= 3 && !bol_hasClear && currentTime - startTime < 1500) {
                            bol_hasClear = true;
                            //检测到在晃动地图，清空地图上的附加物
                            Log.d(TAG, "onTouch:检测到在晃动地图，清空地图上的附加物 ");
                            aMap.clear(true);//只清除marker
                        }

                        break;

                    case MotionEvent.ACTION_UP:
                        //  Log.d(TAG, "onTouch: ACTION_UP");
                        bol_hasClear = false;
                        bol_firstSlide = true;
                        lastX = 0;
                        lastY = 0;
                        changeCount = 0;
                        isShowFirstPushTopic = false;

                }
            }
        });
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                LatLng target = cameraPosition.target;
                if (lastCameraCenter == null) {
                    lastCameraCenter = target;
                    return;
                }
                float zoom = cameraPosition.zoom;
                //当前地图级别下1像素点对应的距离长度（米）
                float scalePerPixel = aMap.getScalePerPixel();
                //搜索半径
                int searchDistance = (int) (scalePerPixel * screenWidth / 2);
                Log.d(TAG, "zoom:" + zoom + "     mBaiduMap.getScalePerPixel(): " + aMap.getScalePerPixel());

                Point targetPoint = aMap.getProjection().toScreenLocation(target);
                Point lastPoint = aMap.getProjection().toScreenLocation(lastCameraCenter);
                lastCameraCenter = target;

                //如果缩放级别改变2个级别
                //如果当前地图中心点与上一次的中心点位置移动距离大于屏幕6分之一，
                // 那么去服务端请求一次 推荐内容
                if ((Math.abs(targetPoint.x - lastPoint.x) > screenWidth / 2 || Math.abs(targetPoint.y - lastPoint.y) > screenHeight / 3)) {
                    nearbySearch(lastCameraCenter, searchDistance);
                } else if (Math.abs(zoom - lastZoom) >= 2) {
                    lastZoom = zoom;
                    nearbySearch(lastCameraCenter, searchDistance);
                }
                Log.d(TAG, "地图移动了，，，，");
            }
        });

        aMap.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker marker) {
                if (marker.getObject() instanceof Topic) {
                    pushTopic = (Topic) marker.getObject();
                    return generateTopicLocationView();
                } else if (marker.getObject() instanceof User) {

                    User targetUser = (User) marker.getObject();

                    return generateUserLocationView(targetUser);

                }
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                return null;
            }
        });


//        mBaiduMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
//            @Override
//            public void onCameraChange(CameraPosition cameraPosition) {
//
//            }
//
//            @Override
//            public void onCameraChangeFinish(CameraPosition cameraPosition) {
//
//                LatLng latLng = cameraPosition.target;
//                //地图移动了，改变罗盘模式为普通模式
//                android.graphics.Point slidePoint = mBaiduMap.getProjection().toScreenLocation(latLng);
//                android.graphics.Point llPoint = mBaiduMap.getProjection().toScreenLocation(locationLatLon);
//                if (slidePoint == null || llPoint == null) {
//                    return;
//                }
//                if ((Math.abs(slidePoint.x - llPoint.x) > screenWidth / 12 || Math.abs(slidePoint.y - llPoint.y) > screenHeight / 12))//
//                {
//                    if (myLocationStyle.getMyLocationType() == MyLocationStyle.LOCATION_TYPE_MAP_ROTATE) {
//                        btnMapstatus.setBackgroundResource(R.drawable.tx_map_location);
//                        mBaiduMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE));//只定位一次，地图和图标都不旋转
//
//                    }
//
//                    //setLocationIcon(null);
//                }
//
//            }
//        });

        //markerClickListener();
    }

    /**
     * 当拖动地图或者缩放地图的时候，搜索当前范围内的主题
     *
     * @param target
     * @param searchDistance
     */
    private void nearbySearch(LatLng target, int searchDistance) {
        if (isNearbySearching) {
            return;
        }
        isNearbySearching = true;
        Map<String, Object> body = new HashMap<>();
        body.put("lat", target.latitude);
        body.put("lon", target.longitude);
        body.put("distance", searchDistance);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .nearbySearch(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        isNearbySearching = false;
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "ES附近失败：" + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "ES附近失败：" + result.getMsg());
                            return;
                        }

                        JSONObject jsonObject = (JSONObject) result.getData();
                        Log.d(TAG, "ES附近完成" + jsonObject);
                        List<Topic> resultsList = JSONObject.parseArray(jsonObject.getString("hits"), Topic.class);
                        // showMultiMarker(resultsList);
                        // location(latLng);
                        //  showMultiPoint(resultsList);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        isNearbySearching = false;
                    }
                });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btn_map_status:
                // android.graphics.Point slidePoint = mBaiduMap.getProjection().toScreenLocation(slidell);
                // android.graphics.Point llPoint = mBaiduMap.getProjection().toScreenLocation(ll);
                //  if (bol_location) //Math.abs(slidePoint.x - llPoint.x) > screenWidth / 4 || Math.abs(slidePoint.y - llPoint.y) > screenHeight / 4
                //   {
                //    location(ll);
                //    bol_location = false;

                //    btnMapstatus.setBackgroundResource(R.drawable.tx_map_navigation_big);
                // slidell = ll;
                //   } else {


            /*    if (myLocationStyle.getMyLocationType() == MyLocationStyle.LOCATION_TYPE_MAP_ROTATE_NO_CENTER) {
                    btnMapstatus.setBackgroundResource(R.drawable.tx_map_location);
                    mBaiduMap.animateCamera(CameraUpdateFactory.changeBearing(0));
                    mBaiduMap.animateCamera(CameraUpdateFactory.changeTilt(50));
                    mBaiduMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE));//只定位一次，定位时自动回到中心点，地图和图标都不旋转
                } else if (myLocationStyle.getMyLocationType() == MyLocationStyle.LOCATION_TYPE_LOCATE) {
                    btnMapstatus.setBackgroundResource(R.drawable.tx_map_navigation_big);
                    //设置地图倾斜度
                    mBaiduMap.animateCamera(CameraUpdateFactory.changeBearing(45));
                    mBaiduMap.animateCamera(CameraUpdateFactory.changeTilt(50));
                    mBaiduMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER));//连续定位图标旋转，不自动回到定位中心点

                } else {
                    btnMapstatus.setBackgroundResource(R.drawable.compass);
                    mBaiduMap.animateCamera(CameraUpdateFactory.changeTilt(50));
                    //  mBaiduMap.animateCamera(CameraUpdateFactory.changeBearing(90));
                    myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.compass));
                    mBaiduMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE_NO_CENTER));//连续定位，地图旋转,不自动回到定位中心点
                }*/

                if (!followMove) {
                    location();
                    followMove = true;
                    btnMapstatus.setBackgroundResource(R.drawable.showbtn);
                    myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.compass3));
                }
//                else if (followMove=true;myLocationStyle.getMyLocationType() == MyLocationStyle.LOCATION_TYPE_SHOW){
//
//                    mBaiduMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE));
//                }

                else if (myLocationStyle.getMyLocationType() == MyLocationStyle.LOCATION_TYPE_LOCATE) {
                    btnMapstatus.setBackgroundResource(R.drawable.tx_map_navigation_big);
                    //设置地图倾斜度
                    aMap.animateCamera(CameraUpdateFactory.changeBearing(45));
                    aMap.animateCamera(CameraUpdateFactory.changeTilt(50));
                    myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.compass2));
                    aMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER));//连续定位图标旋转，不自动回到定位中心点

                } else if (myLocationStyle.getMyLocationType() == MyLocationStyle.LOCATION_TYPE_MAP_ROTATE_NO_CENTER) {
                    btnMapstatus.setBackgroundResource(R.drawable.showbtn);
                    aMap.animateCamera(CameraUpdateFactory.changeBearing(0));
                    aMap.animateCamera(CameraUpdateFactory.changeTilt(50));
                    myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.compass3));
                    aMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE));//只定位一次，定位时自动回到中心点，地图和图标都不旋转

                } else {
                    btnMapstatus.setBackgroundResource(R.drawable.compass);
                    aMap.animateCamera(CameraUpdateFactory.changeTilt(50));
                    //  mBaiduMap.animateCamera(CameraUpdateFactory.changeBearing(90));
                    myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.compass1));
                    aMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE_NO_CENTER));//连续定位，地图旋转,不自动回到定位中心点
                }

                break;
            case R.id.iv_release:

                startActivity(new Intent(getActivity(), PublishTopicActivity.class));

                break;
            case R.id.tv_first_title:
                // TODO: 2019/4/16 切换成热点模式

                tv_first_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_show_title));
                tv_first_title.setTextColor(Color.parseColor("#2e2e2e"));
                tv_second_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_other_title));
                tv_second_title.setTextColor(Color.parseColor("#8E8E8E"));
                tv_third_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_other_title));
                tv_third_title.setTextColor(Color.parseColor("#8E8E8E"));
                break;

            case R.id.tv_second_title:
                // TODO: 2019/4/16 切换成附近模式
                tv_first_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_other_title));
                tv_first_title.setTextColor(Color.parseColor("#8E8E8E"));
                tv_second_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_show_title));
                tv_second_title.setTextColor(Color.parseColor("#2e2e2e"));
                tv_third_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_other_title));
                tv_third_title.setTextColor(Color.parseColor("#8E8E8E"));
                break;
            case R.id.tv_third_title:
                // TODO: 2019/4/16 切换成关注模式
                tv_first_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_other_title));
                tv_first_title.setTextColor(Color.parseColor("#8E8E8E"));
                tv_second_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_other_title));
                tv_second_title.setTextColor(Color.parseColor("#8E8E8E"));
                tv_third_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_show_title));
                tv_third_title.setTextColor(Color.parseColor("#2e2e2e"));
                break;

            case R.id.iv_switch:
                if (listener != null) {
                    listener.onChangeFragment();
                }
                break;

            case R.id.btn3d:
                if (aMap.getMapType() == AMap.MAP_TYPE_SATELLITE) {
                    btn3d.setBackgroundResource(R.drawable.mapswitch02);
                    aMap.setMapType(AMap.MAP_TYPE_NORMAL);
                } else {
                    btn3d.setBackgroundResource(R.drawable.mapswitch03);
                    aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
                }
                break;
            /*case R.id.btn_track_query:

                //定位
                location();
                btnMapstatus.setVisibility(View.VISIBLE);
                btn_trackQuery.setVisibility(View.INVISIBLE);


                break;*/
        }
    }


    private void location(LatLng latLng) {


        aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 16, 30, 30)));//经纬度，缩放级别，倾斜度，角度（可视区域指向的方向）
    }

    //定位
    public void location() {
        aMap.animateCamera(CameraUpdateFactory.changeBearing(0));
        aMap.animateCamera(CameraUpdateFactory.changeTilt(50));
        aMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE));//只定位一次，定位时自动回到中心点，地图和图标都不旋转


    }


    @Override
    public void onMyLocationChange(Location location) {
        //这个回调并不一定是定位成功
        Log.d(TAG, "定位结果：  getLatitude：" + location.getLatitude() + "  getLongitude():" + location.getLongitude());
        if (location.getLatitude() != 0.0 && location.getLongitude() != 0.0) {

            LatLng locationLatLon = new LatLng(location.getLatitude(), location.getLongitude());
            // mapView.postDelayed(() -> location(locationLatLon), 300);
            //   location(locationLatLon);
            if (firstLocation) {
                firstLocation = false;
                autoSearch(locationLatLon);
            }
        } else {
            Log.d(TAG, "onMyLocationChange: 定位失败");
        }
    }


    private void autoSearch(LatLng latLng) {

        Map<String, Object> body = new HashMap<>();
        body.put("lat", latLng.latitude);
        body.put("lon", latLng.longitude);
        body.put("distance", 5);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .autoSearch(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "ES自动搜索失败：" + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "ES自动搜索失败：" + result.getMsg());
                            return;
                        }


                        JSONObject jsonObject = (JSONObject) result.getData();
                        Log.d(TAG, "ES自动搜索完成" + jsonObject);
                        List<Topic> resultsList = JSONObject.parseArray(jsonObject.getString("hits"), Topic.class);
                        showMultiMarker(resultsList);
                        // location(latLng);
                        //  showMultiPoint(resultsList);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    private void showSingleMarker(Topic topic) {

        if (topic == null) {
            return;
        }
        LatLng latLng = new LatLng(topic.getLocation().getLatitude(), topic.getLocation().getLongitude());
        MarkerOptions markerOption = new MarkerOptions()
                .position(latLng)
                .title(topic.getTitle())
                .snippet(topic.getContent());
        Marker maker = aMap.addMarker(markerOption);
        maker.setObject(topic);
        maker.showInfoWindow();
        moveCamera(latLng);
    }

    private void showMultiMarker(List<Topic> resultsList) {
        if (resultsList.size() == 0) {
            return;
        }
        aMap.clear(true);

        isShowFirstPushTopic = true;
        List<LatLng> pointList = new ArrayList<>();
        Marker firstMaker = null;
        for (int i = 0, resultsListSize = resultsList.size(); i < resultsListSize; i++) {
            Topic topic = resultsList.get(i);

            LatLng latLng = new LatLng(topic.getLocation().getLatitude(), topic.getLocation().getLongitude());
            pointList.add(latLng);
            MarkerOptions markerOption = new MarkerOptions()
                    .position(latLng)
                    .title(topic.getTitle())
                    .snippet(topic.getContent());

//            switch (topic.getType()) {
//                case Constant.TOPIC_TYPE_SCHOOL:
//                    markerOption.icon(BitmapDescriptorFactory.fromResource(R.drawable.tx_topic_type_school_4));
//                    break;
//                case Constant.TOPIC_TYPE_EXPOSE:
//                    markerOption.icon(BitmapDescriptorFactory.fromResource(R.drawable.tx_topic_type_expose_4));
//                    break;
//                default:
//                    markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
//            }
//                    markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));

            final Marker maker = aMap.addMarker(markerOption);
            maker.setObject(topic);
            //后端是按主题的评论数量和创建时间等因素排序的，最前面的优先展示给用户
            if (i == 0) {
                firstMaker = maker;
                //maker.showInfoWindow();
            }
        }
        if (firstMaker != null) {
            firstMaker.showInfoWindow();
        }
        zoomToSpanWithCenter(pointList);

    }

    /**
     * 展示海量点
     *
     * @param resultsList
     */
    private void showMultiPoint(List<Topic> resultsList) {
        MultiPointOverlayOptions overlayOptions = new MultiPointOverlayOptions();
        overlayOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));//设置图标
        overlayOptions.anchor(0.5f, 0.5f); //设置锚点
        MultiPointOverlay multiPointOverlay = aMap.addMultiPointOverlay(overlayOptions);

        List<MultiPointItem> list = new ArrayList<MultiPointItem>();

        for (Topic topic : resultsList) {
            LatLng latLng = new LatLng(topic.getLocation().getLatitude(), topic.getLocation().getLongitude());
            MultiPointItem multiPointItem = new MultiPointItem(latLng);
            multiPointItem.setObject(topic);
            list.add(multiPointItem);

        }

        multiPointOverlay.setItems(list);
    }


    public void zoomToSpanWithCenter(List<LatLng> pointList) {
        if (pointList != null && pointList.size() > 0) {
            if (aMap == null)
                return;

            LatLngBounds bounds = getLatLngBounds(pointList.get(0), pointList);
            aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100));
        }
    }

    private void moveCamera(LatLng latLng) {

        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(
                latLng, 18, 30, 30));
        aMap.moveCamera(cameraUpdate);
    }

    //根据中心点和自定义内容获取缩放bounds
    private LatLngBounds getLatLngBounds(LatLng centerpoint, List<LatLng> pointList) {
        LatLngBounds.Builder b = LatLngBounds.builder();
        if (centerpoint != null) {
            for (int i = 0; i < pointList.size(); i++) {
                LatLng p = pointList.get(i);
                LatLng p1 = new LatLng((centerpoint.latitude * 2) - p.latitude, (centerpoint.longitude * 2) - p.longitude);
                b.include(p);
                b.include(p1);
            }
        }
        return b.build();
    }

//    @Override
//    public void onLocationChanged(AMapLocation aMapLocation) {
//
//        //mapview 销毁后不做操作
//        if (aMapLocation == null && mBaiduMap == null)
//            return;
//        // 构造定位数据
//        int mCurrentDirection = 0;
//
//        double mCurrentLat = aMapLocation.getLatitude();
//        double mCurrentLong = aMapLocation.getLongitude();
//        ll = new LatLng(mCurrentLat, mCurrentLong);
//        if (slidell == null) {
//            slidell = ll;
//        }
//
//        // Log.w("经纬度", mCurrentLat+"--"+mCurrentLong);
//        //  pt = new LatLng(mCurrentLat, mCurrentLong);
//        // 设置定位数据
//        //  if (location.get)
//
//      location(new LatLng(mCurrentLat,mCurrentLong));
//        //创建定位光标
//
//        if (isFirstLocation) {
//            isFirstLocation = false;
//            location(ll);
//            //  mLocationClient.stop();
//            if (mCurrentLat != mCurrentLatOld && mCurrentLat != 0.0) {
//                mCurrentLatOld = mCurrentLat;
//
//
//            }
//        }
//    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        this.hidden = hidden;
        if (!hidden) {
            // refreshVideoItem();

        }
    }


    @Override
    public void onResume() {
        super.onResume();
//aMapView.onResume();
        mapView.onResume();
        //  refreshMessageList();
        // updateNoticeUnreadText();
    }

    @Override
    public void onPause() {
        super.onPause();
        // aMapView.onPause();
        mapView.onPause();
//        if (!mLocationClient.isStarted()) {
//            mLocationClient.stopLocation();
//        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // aMapView.onDestroy();
        mapView.onDestroy();
        // mLocationClient.onDestroy();

    }


    public void refresh() {
        // getContactList();
        // updateNoticeUnreadText();
        contactListView.refresh(Helper.getInstance().getContactList());
        //adapter.notifyDataSetChanged();
    }

    private SearchView.OnQueryTextListener getQueryTextListener() {
        SearchView.OnQueryTextListener listener = new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                //开始搜索
                search(query);
                // aMapSearch(et_localSearch, null, "全国", Constant.AMAP_SAERCH_TYPE_LOCAL);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                //可以做搜索建议
                return false;
            }
        };
        return listener;
    }

    private void search(String query) {
        Map<String, Object> info = new HashMap<>();
        info.put("queryContent", query);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .search(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "ES搜索失败：" + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "ES搜索失败：" + result.getMsg());
                            return;
                        }
                        showSearchResult();

                        JSONObject jsonObject = (JSONObject) result.getData();
                        Log.d(TAG, "ES搜索完成" + jsonObject);
                        List<Topic> resultsList = JSONObject.parseArray(jsonObject.getString("hits"), Topic.class);
                        searchResultList.addAll(resultsList);
                        searchResultAdapter.notifyDataSetChanged();
                        //  showToast("查询成功");
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "ES搜索失败：" + t.getMessage());
                    }
                });
    }

    /**
     * 高德云检索
     *
     * @param keyWord
     */
    private void aMapSearch(String keyWord, Integer topicType, String city, int searchType) {
        //https://yuntuapi.amap.com/datasearch/local?tableid=52b155b6e4b0bc61deeb7629&city=北京市&keywords= &filter=type:写字楼&limit=50&page=1&key=<用户key>
        String baseUrl = "https://yuntuapi.amap.com/datasearch/";
        String limit = "20";
        String page = "1";
        switch (searchType) {
            case Constant.AMAP_SAERCH_TYPE_LOCAL:
                baseUrl = String.format(baseUrl + "local?tableid=5ba32b84afdf524990a5456e&key=f0ed15adc5ab80aef60e613ab9ce5fce&keywords=%s &limit=%s &page=%S", keyWord, limit, page);

                if (topicType != null) {
                    baseUrl = baseUrl + "&filter=type:" + topicType;
                }
                if (!TextUtils.isEmpty(city)) {
                    baseUrl = baseUrl + "&city=" + city;
                } else {
                    baseUrl = baseUrl + "&city=全国";
                }
                break;
        }
        Log.d(TAG, baseUrl);
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(baseUrl)
                .get()
                .build();
        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                Log.e(TAG, "高德搜索失败：" + e.getMessage());
                showToast(getString(R.string.system_busy));
            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                if (!response.isSuccessful()) {
                    Log.e(TAG, "高德搜索失败：" + response.message());
                    showToast(getString(R.string.system_busy));
                    return;
                }
                ResponseBody body = response.body();
                if (body == null) {
                    Log.e(TAG, "高德搜索失败：body为空");
                    showToast(getString(R.string.system_busy));
                    return;
                }
                JSONObject result = JSONObject.parseObject(body.string());
                String info = result.getString("infocode");
                if (!TextUtils.equals(info, "10000")) {
                    Log.e(TAG, "高德搜索失败" + result);
                    showToast(getString(R.string.system_busy));
                    return;
                }
                Log.d(TAG, "高德搜索完成" + result);
                int count = result.getInteger("count");
                if (count == 0) {

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showSearchResult();
                        }
                    });
                    return;
                }

                final List<AmapTopic> resultsList = result.getJSONArray("datas").toJavaList(AmapTopic.class);
                for (AmapTopic amapTopic : resultsList) {
                    //把散装的用户信息打包，存进Topic的author字段里面 ,因为后面使用各种信息都是以Topic里面的字段为准，所以在这儿把数据全都存进Topic,AmapTopic 类只是为了方便从高德云检索存取数据
                    User user = new User(amapTopic.getuId());
                    user.setNick(amapTopic.getNick());
                    user.setAvatar(amapTopic.getAvatar());
                    amapTopic.setManager(user);
                    amapTopic.setId(amapTopic.get_id());
                    amapTopic.setTitle(amapTopic.get_name());
                    amapTopic.setAddress(amapTopic.get_address());
                    String[] lonLat = amapTopic.get_location().split(",");
                    amapTopic.setLocation(new com.srwl.mytx.domain.LatLng(Double.valueOf(lonLat[1]), Double.valueOf(lonLat[0])));
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showSearchResult();
                        searchResultList.addAll(resultsList);
                        searchResultAdapter.notifyDataSetChanged();
                    }
                });
            }
        });


    }

    private void showSearchResult() {
        showSearchResult = true;
        if (searchResultAdapter == null) {
            searchResultAdapter = new SearchResultAdapter(getContext(), this, searchResultList);
            searchResultAdapter.setSearchResultItemClickListener(new SearchResultAdapter.SearchResultItemClickListener() {
                @Override
                public void onItemClick(final int position, Topic topic) {

                    // startActivity(new Intent(getContext(), TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, searchResultList.get(position)));
                    // Topic topic = searchResultList.get(position);
                    LatLng latLng = generateTopicMaker(topic);
//                    mBaiduMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
//                        @Override
//                        public boolean onMarkerClick(Marker marker) {
////                            if (!maker.isInfoWindowShown()) {
////
////                                marker.showInfoWindow();
////                            } else {
////                                maker.hideInfoWindow();
////                            }
//                            startActivity(new Intent(getContext(), TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, (Topic) marker.getObject()));
//
//                            return true;
//                        }
//                    });
//                    mBaiduMap.setOnInfoWindowClickListener(new AMap.OnInfoWindowClickListener() {
//                        @Override
//                        public void onInfoWindowClick(Marker marker) {
//                            startActivity(new Intent(getContext(), TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, (Topic) marker.getObject()));
//
//                        }
//                    });
                    location(latLng);
                    // rl_search.setVisibility(View.GONE);
                    searchView.clearFocus();
                }

                @Override
                public void onAddContact(User userInfo, String reason) {
                    //  hideSoftKeyboard();
                    searchView.clearFocus();
                    contactListView.addContact(userInfo, reason);
                }
            });
        }
        //重新设置dapter的时候，需要重新设置新的 LayoutManager
        rl_search.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
        rl_search.setAdapter(searchResultAdapter);
        searchResultList.clear();
    }

    @NonNull
    private LatLng generateTopicMaker(Topic topic) {
        LatLng latLng = new LatLng(topic.getLocation().getLatitude(), topic.getLocation().getLongitude());
        MarkerOptions markerOption = new MarkerOptions()
                .position(latLng)
                .title(topic.getTitle())
                .snippet(topic.getContent());


        markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));

        final Marker maker = aMap.addMarker(markerOption);
        maker.setObject(topic);


        maker.showInfoWindow();
        return latLng;
    }

    @NonNull
    private View generateUserLocationView(User targetUser) {
        View viewInfoWindow = LayoutInflater.from(getActivity()).inflate(R.layout.baidu_maker_infowindow, null);
        viewInfoWindow.getBackground().setAlpha(175);
        TextView tv_name = viewInfoWindow.findViewById(R.id.tv_name);
        TextView tv_address = viewInfoWindow.findViewById(R.id.tv_address);
        TextView tv_time = viewInfoWindow.findViewById(R.id.tv_time);
        View btn_chat = viewInfoWindow.findViewById(R.id.btn_chat);
        ImageView iv_avatar = viewInfoWindow.findViewById(R.id.iv_avatar);
        ImageView iv_navigation = viewInfoWindow.findViewById(R.id.btn_navigation);
        //Glide.with(this).load(targetUser.getAvatar()).placeholder(R.drawable.tx_default_avatar).into(iv_avatar);
        GlideLoadUtils.glideLoad(getActivity(),targetUser.getAvatar(),iv_avatar,R.drawable.tx_default_avatar_1);
        tv_name.setText(targetUser.getUsername());
        tv_address.setText(targetUser.getArea());
        tv_time.setText(DateUtils.getTimestampString(targetUser.getCreated()));
        btn_chat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser));
            }
        });
        iv_navigation.setOnClickListener(v -> showSelectNaviDialog(targetUser.getLatLng().getLongitude(), targetUser.getLatLng().getLatitude(), targetUser.getArea()));
        return viewInfoWindow;
    }

    @NonNull
    private View generateTopicLocationView() {

        View view = LayoutInflater.from(getContext()).inflate(R.layout.topic_infowindow_layout, null);
        TextView tv_title = view.findViewById(R.id.tv_title);
        //TextView tv_content = view.findViewById(R.id.tv_content);
        ImageView iv_topicType = view.findViewById(R.id.iv_topic_type);
        tv_title.setText(pushTopic.getTitle());
        // tv_content.setText(topic.getContent());

        if (pushTopic.getType() != null) {

            switch (pushTopic.getType()) {
                case Constant.TOPIC_TYPE_LOST_PEOPLE:
                    iv_topicType.setImageResource(R.drawable.tx_topic_type_lost_person);
                    break;
               /* case Constant.TOPIC_TYPE_LOST_THING:
                    iv_topicType.setImageResource(R.drawable.tx_topic_type_lost_thing);
                    break;*/
                case Constant.TOPIC_TYPE_EXPOSE:
                    //    tv_title.setTextColor(getResources().getColor(R.color.topic_type_expose_red));
                    iv_topicType.setImageResource(R.drawable.tx_topic_type_expose_3);
                    break;
                case Constant.TOPIC_TYPE_FOUND:
                    iv_topicType.setImageResource(R.drawable.tx_topic_type_found);
                    break;
                case Constant.TOPIC_TYPE_GIFT:
                    iv_topicType.setImageResource(R.drawable.tx_topic_type_gift);
                    break;
                case Constant.TOPIC_TYPE_AUCTION:
                    iv_topicType.setImageResource(R.drawable.tx_topic_type_auction);
                    break;
                case Constant.TOPIC_TYPE_GOODS:
                    iv_topicType.setImageResource(R.drawable.tx_topic_type_goods);
                    break;
                case Constant.TOPIC_TYPE_SHOW:
                    iv_topicType.setImageResource(R.drawable.tx_topic_type_show);
                    break;

                case Constant.TOPIC_TYPE_AREA:
                    iv_topicType.setImageResource(R.drawable.tx_topic_type_area);
                    break;

                case Constant.TOPIC_TYPE_INDUSTRY:
                    iv_topicType.setImageResource(R.drawable.tx_topic_type_industry);
                    break;

                case Constant.TOPIC_TYPE_SCHOOL:
                    iv_topicType.setImageResource(R.drawable.tx_topic_type_school_5);
                    //   tv_title.setTextColor(getResources().getColor(R.color.topic_type_school_orange));

                    break;

            }
        }
        // InfoWindowView infoWindowView = new InfoWindowView(getContext(), searchResultList.get(position));
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(getActivity(), TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, pushTopic), REQUEST_CODE_TO_TOPIC_DETAIL_FROM_PUSH_MESSAGE);
            }
        });
        return view;
    }

    private void showProgressBar(boolean isShowProgressBar) {
        if (isShowProgressBar && !progressBar.isShown()) {
            progressBar.setVisibility(View.VISIBLE);
        } else if (!isShowProgressBar && progressBar.isShown()) {
            progressBar.setVisibility(View.GONE);
        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {


        amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
        double latitude = amapLocation.getLatitude();//获取纬度
        double longitude = amapLocation.getLongitude();//获取经度
        amapLocation.getAccuracy();//获取精度信息

        Log.d(TAG, "onLocationChanged: latitude" + latitude + " latitude" + longitude);
        location(new LatLng(latitude, longitude));
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
        aMap.setMyLocationStyle(myLocationStyle);

    }

    /**
     * 附近发现红包
     *
     * @param intent
     */
    public void foundCoupon(Intent intent) {
        Topic couponTopic = intent.getParcelableExtra("couponTopic");
        showSingleMarker(couponTopic);

    }


    public class MyItemTouchHelperCallBack extends ItemTouchHelper.Callback {
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            if (showSearchResult) {
                return ItemTouchHelper.ACTION_STATE_IDLE;
            }
            if (viewHolder.getAdapterPosition() == searchHistoryAdapter.getItemCount() - 1) {
                return ItemTouchHelper.ACTION_STATE_IDLE;
            }
            int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            return makeMovementFlags(dragFlags, swipeFlags);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            Log.d(TAG, "onSwiped: 滑动删除，，，，");
           // searchHistoryAdapter.removeSearchHistory(viewHolder.getAdapterPosition());
            // TODO: 2019-10-07
        }
    }

    public boolean onBackClick() {

        if (!searchView.isFocused() && rl_search.isShown()) {
            searchView.onActionViewCollapsed();
            closeSearchView();
            return true;
        }
        return false;
    }

    void closeSearchView() {
        searchView.setBackground(new ColorDrawable(Color.TRANSPARENT));
        rl_search.setVisibility(View.GONE);
    }


    public List<String> getApkList(Context context) { //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        return packageNames;
    }

    private List<String> getMapApk() {
        List<String> itemList = new ArrayList<>();
        List<String> apkList = getApkList(getActivity());
        if (apkList.contains("com.autonavi.minimap")) {

            itemList.add("高德地图");
        }
        if (apkList.contains("com.baidu.BaiduMap")) {
            itemList.add("百度地图");
        }
        if (apkList.contains("com.tencent.map")) {

            itemList.add("腾讯地图");
        }

        return itemList;
    }

    private void showSelectNaviDialog(double longitude, double latitude, String address) {

        List<String> mapApk = getMapApk();
        if (mapApk.size() == 0) {
            showToast("在您手机上暂未找到导航软件...");
            return;
        }
        BottomDialog bottomDialog = new BottomDialog(getActivity(), mapApk, new BottomDialog.InteractionListener() {
            @Override
            public void onDialogItemViewClick(int position, String itemName) {
                Intent intent;
                switch (itemName) {
                    case "高德地图":

//
//                        intent = new Intent("androidamap://route?sourceApplication=" + getResources().getString(R.string.app_name) + "&sname=我的位置&dlat="
//                                + latitude + "&dlon=" + longitude + "&dname=" + "标题" + "&dev=1&m=2&t=3");
//                        startActivity(intent);
                        String uriString = null;
                        StringBuilder builder = new StringBuilder("amapuri://route/plan?sourceApplication=" + getResources().getString(R.string.app_name));
                        builder.append("&dlat=").append(latitude)
                                .append("&dlon=").append(longitude)
                                .append("&dname=").append(address)
                                .append("&dev=0")
                                .append("&t=0");
                        uriString = builder.toString();
                        intent = new Intent(Intent.ACTION_VIEW);
                        intent.setPackage("com.autonavi.minimap");
                        intent.setData(Uri.parse(uriString));
                        startActivity(intent);

                        break;

                    case "百度地图":
                        intent = new Intent();
                        // double[] doubles = gaoDeToBaidu(latitude, longitude);
                        intent.setData(Uri.parse("baidumap://map/direction?coord_type=gcj02&destination=" + latitude + "," + longitude + "&mode=driving"));
                        startActivity(intent);

                        break;

                    case "腾讯地图":
//                        intent = new Intent();
//                        intent.setAction(Intent.ACTION_VIEW);
//                        intent.addCategory(Intent.CATEGORY_DEFAULT);
//                        //将功能Scheme以URI的方式传入data
//                        Uri uri = Uri.parse("qqmap://map/routeplan?type=drive&to=" + address + "&tocoord=" + latitude + "," + longitude);
//                        intent.setData(uri);
//                        startActivity(intent);

                        String uriString1 = null;
                        StringBuilder builder1 = new StringBuilder("qqmap://map/routeplan?type=drive&policy=0&referer=zhongshuo");

                        builder1.append("&to=").append(address)
                                .append("&tocoord=").append(latitude)
                                .append(",")
                                .append(longitude);
                        uriString = builder1.toString();
                        intent = new Intent(Intent.ACTION_VIEW);
                        intent.setPackage("com.tencent.map");
                        intent.setData(Uri.parse(uriString));
                        startActivity(intent);

                        break;

                }
            }
        });
        bottomDialog.show();

    }


    /**
     * @author Administrator
     * @time 2018/5/14  13:35
     * @describe 高德转百度（火星坐标gcj02ll–>百度坐标bd09ll）
     */
    @Deprecated
    public double[] gaoDeToBaidu(double gd_lat, double gd_lon) {
        double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        double x = gd_lon, y = gd_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        double tempLon = z * Math.cos(theta) + 0.0065;
        double tempLat = z * Math.sin(theta) + 0.006;
        double[] gps = {tempLat, tempLon};
        return gps;
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_CODE_TO_TOPIC_DETAIL_FROM_SEARCH) {
            Topic updateTopic = data.getParcelableExtra("topic");

            for (int i = 0; i < searchResultList.size(); i++) {
                Topic topic = searchResultList.get(i);
                if (topic.getId().equals(updateTopic.getId())) {
                    searchResultList.remove(i);
                    searchResultList.add(i, updateTopic);
                    break;
                }
            }
        } else if (requestCode == REQUEST_CODE_TO_TOPIC_DETAIL_FROM_PUSH_MESSAGE) {
            Topic updateTopic = data.getParcelableExtra("topic");
            pushTopic = updateTopic;


        }
    }
}

